#!/usr/bin/env Rscript

## ####################
## Package Dependencies
## ####################

suppressMessages({
    library("oc")
    library("pscl")
    library("wnominate")
    library("foreach")
    library("doRNG")
    library("emIRT")
}
                 )

## ##############
## Define Handoff
## ##############

BATON <- new.env()

## ################
## Env Dependencies
## ################

est_type <- Sys.getenv("TYPE")
isDistMem <- as.integer(Sys.getenv("DISTMEM"))
nProcs <- as.integer(Sys.getenv("PROCS"))
nPPN <- as.integer(Sys.getenv("PPN"))
nNodes <- as.integer(Sys.getenv("NODES"))
nMC <- as.integer(Sys.getenv("MC"))
cCHAM <- Sys.getenv("CHAM")
isThreaded <- as.integer(Sys.getenv("THREADED"))

## ############################
## Shared or Distributed Memory
## ############################

if (isDistMem == 1) {
    cat("\nDIST MEM\n")
    suppressMessages({
        library("doMPI")
    }
                     )
    cl <- startMPIcluster(verbose = FALSE)
    registerDoMPI(cl)
} else {
    cat("\nsingle node\n")
    suppressMessages({
        library("doMC")
    }
                    )
    registerDoMC(nProcs)
}
registerDoRNG()


## ############
## Set Up Paths
## ############

p2root <- "../../../"
p2common <- file.path(p2root, "../common/")
p2funcs <- paste(p2root, "src/R/functions/", sep = "")
p2rc <- paste(p2common, "data/RDA/rollcalls/", sep = "")
p2leaders <- paste(p2root, "data/CSV/leaders/", sep = "")
p2output <- paste(p2root, "data/RDATA/estimates/", est_type, "/", cCHAM, ".Rdata", sep = "")

BATON$p2rc <- p2rc

## #################
## Data Dependencies
## #################

dfLeaders <- read.csv(paste(p2leaders, "leaders.csv", sep = ""))
dfLeaders$chamber2 <- ifelse(dfLeaders$chamber == "H", "hou", "sen")
BATON$dfLeaders <- dfLeaders
                                        # Put manipulated dfLeaders into Env

source(paste(p2funcs, "estimator.R", sep = ""),
       local = BATON
       )


## #######################
## Define Scope of Problem
## #######################
vSess <- 102:112
vMC <- 1:nMC

dfGrid <- expand.grid(cham = cCHAM, sess = vSess, mc = vMC, type = est_type)
BATON$dfGrid <- dfGrid

## #####################
## Estimate Ideal Points
## #####################
set.seed(1)

print(dfGrid)

g <- 1

lOut <- foreach(g = 1:nrow(dfGrid),
                .export = "BATON"
                ) %dopar% {
                    ## sink("where.txt", append=TRUE)
                    ## cat(Sys.info())
                    ## cat("\n")
                    ## sink()

                    ## #########################
                    ## Attach Handed Off Objects
                    ## #########################

                    attach(BATON)

                    ## ##################
                    ## Get Current Params
                    ## ##################

                    cham <- as.character(dfGrid$cham[g])
                    sess <- dfGrid$sess[g]

                    load(paste(p2rc, "/", cham, sess, ".rda", sep = ""))
                    rc <- rcs$all
                    ## rc <- lRCs[[cham]][[as.character(sess)]][["rc"]]

                    ## #####################################
                    ## Get Pre-Defined Normalization Anchors
                    ## #####################################
                    canchor <- subset(dfLeaders,
                                      subset = ((session == sess) &
                                                (chamber2 == cham) &
                                                (party == "R")
                                                )
                                      )$id_icpsr[1]

                    lanchor <- subset(dfLeaders,
                                      subset = ((session == sess) &
                                                (chamber2 == cham) &
                                                (party == "D")
                                                )
                                      )$id_icpsr[1]

                    cidx <- which(rc$legis.data$icpsrLegis == canchor)
                    lidx <- which(rc$legis.data$icpsrLegis == lanchor)

                    ## #######################
                    ## Run and Time Estimation
                    ## #######################
                    timing <- system.time({
                        out <- estimator(.rc = rc,
                                         .type = as.character(dfGrid$type[g]),
                                         .polarity = c(canchor, lanchor)
                                         )
                    }
                                          )

                    return(list(cham = cham,
                                sess = sess,
                                ## rc = rc,
                                canchor = canchor,
                                lanchor = lanchor,
                                output = out,
                                time = timing,
                                mc = dfGrid$mc[g],
                                hostname = Sys.info()[4]
                                )
                           )
                }

## ###########
## Save Output
## ###########
save(lOut,
     file = p2output,
     compress = "bzip2"
     )

## #####################
## Shut Down Dist Memory
## #####################
if (isDistMem == 1) {
    closeCluster(cl)
    mpi.quit()
}

################################################################################
